﻿/*
 * 通用值转换
 */



public static class Extensions
{
    /// <summary>
    /// 可为空的值转换会报错
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static T Parse<T>(this object obj)
    {
        var newValue = Convert.ChangeType(obj, typeof(T));
        return (T)newValue;
    }

    public static T? ParseNew<T>(this object obj, T? defaultValue = default)
    {
        var type = typeof(T);
        try
        {
            var nullableType = Nullable.GetUnderlyingType(type); //判断这个类型是否可为空 
            if (nullableType is not null)
            {
                return (T)Convert.ChangeType(obj, nullableType);
            }
            return (T)Convert.ChangeType(obj, type);

        }
        catch (Exception e)
        {
            return defaultValue;
        }
    }
}